/**
 * API工具函数
 */
import CryptoJS from 'crypto-js';
import { API_CONFIG } from './config';

/**
 * 生成随机字符串
 * @param {number} length - 字符串长度
 * @returns {string} - 随机字符串
 */
export function generateNonceStr(length = 20) {
  const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

/**
 * 生成签名（按Unicode码点排序）
 * @param {Object} params - 请求参数
 * @returns {string} - 签名
 */
export function generateSignature(params) {
  // 按照Unicode码点排序
  const sortedKeys = Object.keys(params).sort((a, b) => {
    // 将字符串转换为码点数组进行比较
    const aPoints = Array.from(a).map(c => c.codePointAt(0));
    const bPoints = Array.from(b).map(c => c.codePointAt(0));
    
    for (let i = 0; i < Math.min(aPoints.length, bPoints.length); i++) {
      if (aPoints[i] !== bPoints[i]) {
        return aPoints[i] - bPoints[i];
      }
    }
    return aPoints.length - bPoints.length;
  });
  
  // 构建待签名字符串
  let signStr = '';
  sortedKeys.forEach(key => {
    const value = params[key];
    if (value !== undefined && value !== null && value !== '') {
      // 如果是对象，需要序列化
      const valueStr = typeof value === 'object' ? JSON.stringify(value) : String(value);
      signStr += `${key}${valueStr}`;
    }
  });
  
  // 加上密钥
  signStr = API_CONFIG.secretKey + signStr + API_CONFIG.secretKey;
  
  // 使用HMAC-SHA256加密并转为Base64
  const hash = CryptoJS.HmacSHA256(signStr, API_CONFIG.secretKey);
  return CryptoJS.enc.Base64.stringify(hash);
}

/**
 * 构建请求参数（新API格式）
 * @param {string} interfaceCode - 接口编码
 * @param {Object} data - 业务数据
 * @returns {Object} - 完整请求参数
 */
export function buildRequestParams(interfaceCode, data = {}) {
  return{
    interfaceCode,
    data
  }
  const timestamp = String(Date.now()); // 13位时间戳
  const nonceStr = generateNonceStr();
  
  const requestParams = {
    interfaceCode,
    timestamp,
    nonceStr,
    data
  };
  
  // 生成签名
  const signature = generateSignature(requestParams);
  
  return {
    ...requestParams,
    signature
  };
}
